<?php

declare(strict_types=1);

namespace DreamCat\Array2Class\TransImpl;

use DreamCat\Array2Class\PropertyNameTransInterface;
use JetBrains\PhpStorm\Pure;

/**
 * 驼峰转下划线
 * @author vijay
 */
class CamelCase2UnderLine implements PropertyNameTransInterface
{
    /** @var string 匹配正则 */
    private const PREG = "#(?<!^)(?<!_)[A-Z]#";

    /**
     * @inheritDoc
     * @noinspection PhpPureFunctionMayProduceSideEffectsInspection
     */
    #[Pure]
    public function convert(string $propertyName): string
    {
        $ret = preg_replace_callback(
            self::PREG,
            [
                $this,
                "replace",
            ],
            $propertyName
        );
        return strtolower($ret);
    }

    /**
     * 替换函数
     * @param string[] $match 正则匹配到的部分
     * @return string 要替换的部分
     */
    #[Pure]
    private function replace(array $match): string
    {
        return "_{$match[0]}";
    }
}

# end of file
